#coding=utf-8
#房间管理，默认初始化100个房间
import mg_master

MAXROOMS = 100
SINGLEROOMMAX = 1
TOTALUSERSINSINGLEROOM=2
rooms = []

#初始化100个房间，每个房间内分为A，B两方,暂定一方一人，结果判定状态标志位，返回结果记数
for id in xrange(MAXROOMS):
		room = {"armyA":[],"armyB":[],"users":[],"que":0}
		rooms.append(room)


#在客户端指定房间ID
def addUserToRoom(roomid,userid):
	room = rooms[int(roomid)]
	len_A = len(room["armyA"])
	len_B = len(room["armyB"])
	if len_A != SINGLEROOMMAX or len_B != SINGLEROOMMAX: 
		if len_A <= len_B:
			room["armyA"].append(userid)
			#更新用户所在房间ARMYA
			updateRoom(roomid,userid,"armyA")
			if len(room["armyA"]) == SINGLEROOMMAX and len(room["armyB"]) == SINGLEROOMMAX: 
				return "fullarmy",getUsersByRoomId(roomid)
			else:
				return "armyA",None
		else:
			#更新用户所在房间ARMYB
			updateRoom(roomid,userid,"armyB")
			room["armyB"].append(userid)
			if len(room["armyA"]) == SINGLEROOMMAX and len(room["armyB"]) == SINGLEROOMMAX: 
				return "fullarmy",getUsersByRoomId(roomid)
			else:
				return "armyB",None

#删除客户
def removeUserFromRoom(user):
	if user.getRoomId() != None:
		try:
			rooms[int(user.getRoomId())][user.getArmy()].remove(user.getId())
			print "<-- Room remove user success -->",user.getId()
		except:
			print "<-- Room remove faile -->"

#按房间ID返回房间内的用户
def getUsersByRoomId(id):
	users = []
	for usr in rooms[int(id)]["armyA"]:
		users.append(mg_master.cache.getUser(usr))

	for usr in rooms[int(id)]["armyB"]:
		users.append(mg_master.cache.getUser(usr))

	return users

#平均房间内每次战斗结果并更新缓存
def makeJudge(_users):
	
	roomid = mg_master.cache.getUser(int(_users[0]["id"])).getRoomId()
	rooms[int(roomid)]["que"] = rooms[int(roomid)]["que"] + 1
	

#	import rpdb2; rpdb2.start_embedded_debugger("melissa")

	if rooms[int(roomid)]["que"] == TOTALUSERSINSINGLEROOM:
			
			rooms[int(roomid)]["users"].append(_users)
			tempHealths = {}
			varusers = getUsersByRoomId(int(roomid))
			for varuser in varusers:
				tempHealths[str(varuser.getId())] = 0 
			
			for users in rooms[int(roomid)]["users"]:
				for user in users:
					tempHealths[user["id"]] = tempHealths[user["id"]] + int (user["health"])
					print user["id"],tempHealths[user["id"]]

			for k,v in tempHealths.items():
				avhealth = v/len(tempHealths)
				mg_master.cache.updateUserHealth(int(k),int(avhealth))
		
			rooms[int(roomid)]["que"] = 0
			return getUsersByRoomId(int(roomid))
	else:
		rooms[int(roomid)]["users"].append(_users)
		return False


#更新用户所选择房间ID
def updateRoom(_userid,_roomid,_army):
	mg_master.cache.updateUserRoom(_roomid,_userid,_army)




